﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aierp.Entities;
using Aierp.Repository;
using Aierp.Repository.Implements;
using Aierp.Repository.Models;
using Aierp.SystemEntities.System;
using Aierp.Utility;
using Aierp.Utility.Core;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace Aierp.Controllers
{
    [Route("api/[controller]")]
    public class RoleNavBtnsController : ControllerBase
    {
        RoleNavBtnsRepository Repository { get; set; }
        SysVisitor SysVisitor { get; set; }
        public RoleNavBtnsController(RoleNavBtnsRepository repository, SysVisitor sysVisitor)
        {
            Repository = repository;
            SysVisitor = sysVisitor;
        }

        [HttpGet("GetTree/{id}")]
        public async Task GetTree(int id)
        {
            var list = Repository.FindByRoles(id);
            if (list == null)
            {
                await WriteFailJson();
                return;
            }
            var ret = list.Select(c => new { KeyId = c.NavId, state = true});
            //return JSONhelper.ToJson(ret);

            await WriteResultJson(ret);
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public async void Put(int id)
        {
            //检查用户是否有权限操作
             if (!await CheckUser(SysVisitor)) return;;

            //获取用户对象
            var request = HttpContext.Request;
            var json = request.Form["model"];
            var requestModels = JSONhelper.ConvertToObject<List<CheckedListModel>>(json);

            var models = requestModels.Where(c => c.status == true).Select(s => new Sys_RoleNavBtns{ RoleId = id, NavId = s.id}).ToList();
            if (Repository.ChangeRoles(models,id) > 0)
            {
                await this.WriteSucessJson();
            }
            else
            {
                await this.WriteFailJson();
            }

        }
    }
}
